import React from 'react';
import { Table, Form, Checkbox } from 'antd';
import { size } from 'lodash';
import { AUTH, GRADE } from '../../constant';
// import styles from './index.less';

const isProd = process.env.ENV === 'production';

/**
 *@description 获取树选中所有子孙值
 * @param {Object} datasource 选中的树节点
 */
const getChildrenData = datasource => {
    if (size(datasource) > 0) {
        const tempArr = [];
        // 递归获取数据
        const deepFn = node => {
            tempArr.push(node.code);
            if (Array.isArray(node.children)) {
                node.children.forEach(item => {
                    deepFn(item);
                });
            }
        };
        deepFn(datasource);
        return tempArr;
    }
    return [];
};
const AuthTable = ({ data, resourceCodes, onCheckChange }) => {
    const handleCheckChange = (e, text, record) => {
        let tempArr = [];
        if (onCheckChange) {
            if (e.target.checked === true) {
                tempArr = getChildrenData(record);
            }
            onCheckChange(e.target.checked, text, record, tempArr);
        }
    };

    const columns = [
        {
            title: '功能',
            dataIndex: 'name',
            render: (text, record) => (isProd ? text : <span title={record.code}>{text}</span>)
        },
        {
            title: '类型',
            dataIndex: 'type',
            render: text => AUTH[text] || ''
        },
        {
            title: '等级',
            dataIndex: 'gradeType',
            render: text => {
                if (text === 3) {
                    return <span style={{ color: '#f5222d' }}>{GRADE[text]}</span>;
                }
                return GRADE[text] || '';
            }
        },
        {
            title: '操作',
            dataIndex: 'code',
            render: (text, record) => (
                <Checkbox
                    checked={resourceCodes.includes(text)}
                    // disabled={record.gradeType === 1 || defaultResourceCodes.includes(text)}
                    onChange={e => handleCheckChange(e, text, record)}
                ></Checkbox>
            )
        }
    ];

    return (
        data.length > 0 && (
            <Table
                bordered={false}
                dataSource={data}
                columns={columns}
                rowKey="code"
                pagination={false}
                style={{ marginTop: 16 }}
                defaultExpandAllRows
            />
        )
    );
};

export default Form.create()(AuthTable);
